﻿using Manon.Core.Commons;
using Manon.Core.Exception;
using Manon.Core.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;

namespace Manon.Core.Filters
{
    /// <summary>
    /// api异常过滤器
    /// </summary>
    public class ApiExceptionFilter : IExceptionFilter
    {
        private readonly ILogger<ApiExceptionFilter> _logger;

        public ApiExceptionFilter(ILogger<ApiExceptionFilter> logger)
        {
            _logger = logger;
        }

        public void OnException(ExceptionContext context)
        {
            string methodInfo = $"{context.RouteData.Values["controller"] as string}Controller.{context.RouteData.Values["action"] as string}:{context.HttpContext.Request.Method}";

            _logger.LogError(context.Exception, "执行{0}时发生错误！", methodInfo);


            context.Result = new JsonResult(null)
            { 
                StatusCode = (int)StateCode.Ok,
                Value = ApiResult.ErrorResult(context)
            };
        }
    }
}
